package demo.aes;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import cn.bingoo.lang.Encoding;

public class AesDemo {
    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("helloworld");
        System.out.println(encrypt);
    }

    static KeyGenerator kg = null;
    static Cipher c = null;
    static Key k = null;
    static byte[] ivector = null;

    static IvParameterSpec iv = new IvParameterSpec("1234567812345678".getBytes());//使用CBC模式，需要一个向量iv，可增加加密算法的强度  

    static public String encrypt(String data) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(256);
        c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        k = kg.generateKey();

        byte[] keyBytes = "abcdefghijklmnopqrstuvwxyz123456".getBytes("UTF-8");
        SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
        c.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] ciphertext = c.doFinal(data.getBytes("UTF-8"));

        return Encoding.base64encode(ciphertext, false);
    }

    static public String decrypt(String data) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("AES");
        kg.init(256);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec("abcdefghijklmnopqrstuvwxyz123456".getBytes("UTF-8"), "AES");
        c.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] originalText = Encoding.base64decode(data, false);
        byte[] plaintext = c.doFinal(originalText);

        return new String(plaintext, "UTF-8");
    }

}
